package cn.edu.zafu.bigdata.lyq.work7;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class FileAppend {

    // 将文本追加到文件的方法
    public static void appendToFile(String fileName, String content) {
        try {
            FileWriter writer = new FileWriter(fileName, true);
            writer.write(content);
            writer.close();
            System.out.println("文本已成功追加到文件。");
        } catch (IOException e) {
            System.out.println("追加文件内容时出错：" + e.getMessage());
        }
    }

    // 读取文件内容并打印的方法
    public static void readFile(String fileName) {
        try {
            File file = new File(fileName);
            Scanner scanner = new Scanner(file);

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }

            scanner.close();
        } catch (FileNotFoundException e) {
            System.out.println("读取文件时出错：找不到文件 " + fileName + "，错误信息：" + e.getMessage());
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        String fileName = "202203090213.txt";

        System.out.println("请输入要追加到文件的文本内容：");
        String inputText = scanner.nextLine();

        appendToFile(fileName, inputText);

        readFile(fileName);

        scanner.close();
    }
}